package com.Semaphore;

import java.util.concurrent.Semaphore;

/**
 * Created by mike on 17/10/25.
 */
public class SemaphoreTest {
    private Semaphore semaphore;

    public SemaphoreTest(int count) {
        this.semaphore = new Semaphore(count);
    }

    public static void main(String[] args) throws InterruptedException {
        final SemaphoreTest semaphoreTest = new SemaphoreTest(2);
        for(int i=0;i<13;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphoreTest.getConnection();
                        System.out.println(Thread.currentThread().getName()+"处理业务。。。");
                        Thread.sleep(3000);
                        semaphoreTest.closeConnection();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
//            semaphoreTest.getConnection();
//            System.out.println(Thread.currentThread().getName()+"处理业务。。。"+i);
        }

    }

    public void getConnection() throws InterruptedException {
        this.semaphore.acquire();
        System.out.println(Thread.currentThread().getName()+"getConnection");
    }

    public void closeConnection() {
        System.out.println(Thread.currentThread().getName()+"closeConnection");
        this.semaphore.release();
    }
}
